package com.portal.config.interceptor;

import com.portal.exception.Assert;
import com.portal.result.impl.BusinessCode;
import com.portal.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录校验拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    // 执行控制器方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("访问的资源路径：{}",request.getRequestURI());

        //1. 判断是否是options请求，如果是则直接放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        //2. 获取请求头
        String token = request.getHeader("Authorization");
        //3. 判断token是否存在
        Assert.error(!StringUtils.hasText(token), BusinessCode.USER_NOT_LOGGED);
        //4. 验证token是否有效
        Assert.error(!jwtUtil.validateToken(token), BusinessCode.INVALID_TOKEN);

        //5. 判断IP地址是否相同
        String lastLoginIp = jwtUtil.getValue(token, "ip");
        //Assert.error(!lastLoginIp.equals(jwtUtil.getRequestIP(request)), BusinessCode.INVALID_IP);
        //6. 如果都通过则放行
        return true;
    }
}
